import store from "../../store";
import {
  COMMIT_COMMAND
} from "../../store/events";

import eventBus from "../EventBus";
import {
  LOG_TO_SCREEN
} from "../EventBus/events";

import logParser from "../LogParser";

// 消息分发器，在 ws 接收到消息时使用
export default function messageDistributer(message, isInit) {
  if (typeof message === "string") {
    message = JSON.parse(message);
  }
  if (message.type === "command") {
    if (message.user !== store.state.username || isInit) {
      // 非自己发送的消息，才进行提交
      store.dispatch(COMMIT_COMMAND, {
        command: message,
        onlyExecute: true
      });
    }
  } else if (message.type === "room") {
    // 进行解析后再 log
    eventBus.$emit(LOG_TO_SCREEN, logParser(message));
  } else {
    throw "Error: 错误的消息类型"
  }
}